﻿/*
=======================================================
    User【用户】
=======================================================
*/

using System.Collections.Generic;
using System.Net.NetworkInformation;
using Entities;

namespace Services
{
    public interface IUserLogic : ILogic<UserModel, UserFilterModel>
    {
        int UpdateIsDelete(bool flag, params int[] ids);
        UserModel GetUserByLogin(string code, string loginName, string password);
        Me GetMe();
        void ResetPassword(List<int> ids, string pwd);
        List<UserModel> GetUserListByDepartmentID(int departmentID);
        void EditPassword(EditPasswordModel model);
    }


    public class UserLogic : BaseLogic<UserModel, UserFilterModel, User, IUserRepository, IUserMapping, IUserService>, IUserLogic
    {
        #region Ioc
        private readonly IUserRoleRepository _IUserRoleRepository;
        private readonly IRoleRepository _IRoleRepository;
        private readonly IDepartmentUserRepository _IDepartmentUserRepository;
        private readonly IDepartmentRepository _IDepartmentRepository;
        private readonly IDataDepartmentRepository _IDataDepartmentRepository;
        private readonly IPermissionRepository _IPermissionRepository;
        private readonly IRegulatorUserRepository _IRegulatorUserRepository;
        private readonly ISuperUserRepository _ISuperUserRepository;

        public UserLogic(ICurrentUser currentUser, IUserRepository repository, IUserMapping mapping, IUserService service,
            IUserRoleRepository iUserRoleRepository, IRoleRepository iRoleRepository,
            IDepartmentUserRepository iDepartmentUserRepository, IDepartmentRepository iDepartmentRepository, IDataDepartmentRepository iDataDepartmentRepository,
            IPermissionRepository iPermissionRepository, IRegulatorUserRepository iRegulatorUserRepository, ISuperUserRepository iSuperUserRepository)
            : base(currentUser, repository, mapping, service)
        {
            _IUserRoleRepository = iUserRoleRepository;
            _IRoleRepository = iRoleRepository;
            _IDepartmentUserRepository = iDepartmentUserRepository;
            _IDepartmentRepository = iDepartmentRepository;
            _IDataDepartmentRepository = iDataDepartmentRepository;
            _IPermissionRepository = iPermissionRepository;
            _IRegulatorUserRepository = iRegulatorUserRepository;
            _ISuperUserRepository = iSuperUserRepository;
        }
        #endregion

        #region 启用/禁用  UpdateIsDelete
        public int UpdateIsDelete(bool flag, params int[] ids)
        {
            return _repository.UpdateIsDelete(flag, ids);
        }
        #endregion

        #region GetUserByLogin
        public UserModel GetUserByLogin(string code, string loginName, string password)
        {
            var users = _repository.GetUserByLogin(code, loginName, password);
            if (users.Count != 1)
            {
                throw new CustomException("用户代码、用户名、密码输入错误！");
            }

            var first = users.First();

            return new UserModel
            {
                LoginUserType = Gx.GetEnumByValue<LoginUserType>(first.LoginUserType),
                LoginTypeID = first.LoginTypeID,
                UserID = first.UserID,
                Name = first.Name,
            };
        }
        #endregion

        #region GetMe
        public Me GetMe()
        {
            var me = new Me();

            me.Name = _currentUser.CurrentUserInfo.UserName;
            me.UserID = _currentUser.CurrentUserInfo.UserID;
            me.LoginUserType = _currentUser.CurrentUserInfo.LoginUserType;
            me.RoleIDs = _IUserRoleRepository.GetMeRoleIDs();

            var allPermissions = _IPermissionRepository.GetAll();
            var mePermissionIDs = _IPermissionRepository.GetLoginUserPermissionIDs();

            foreach (var item in allPermissions)
            {
                item.IsPermission = mePermissionIDs.Any(x => x == item.PermissionID);
            }

            foreach (var lv1 in allPermissions.Where(x => x.ParentID == 0).ToList())
            {
                lv1.IsPermission = allPermissions.Where(x => x.GroupNum == lv1.GroupNum).Any(x => x.IsPermission == true);

                foreach (var lv2 in allPermissions.Where(x => x.ParentID == lv1.PerID).ToList())
                {
                    lv2.IsPermission = allPermissions.Where(x => x.ParentID == lv2.PerID).Any(x => x.IsPermission == true);
                }
            }

            me.Permissions = allPermissions.Select(x => new
            {
                PerID = x.PerID,
                Name = x.Name,
                IsPermission = x.IsPermission,
                ParentID = x.ParentID,
                GroupNum = x.GroupNum,
            }).ToList();

            return me;
        }
        #endregion

        #region GetPage
        public override PageModel<UserModel> GetPage(UserFilterModel filterModel, int pageIndex = 1, int pageSize = 20, string orderBy = null)
        {
            var pageData = base.GetPage(filterModel, pageIndex, pageSize, orderBy);

            var userDepartmentList = _IDepartmentUserRepository.GetAll();
            var departmentList = _IDepartmentRepository.GetAll();
            var userRoleList = _IUserRoleRepository.GetAll();
            var roleList = _IRoleRepository.GetAll();


            //获取当前用户应该有的数据权限范围
            var (isAll, dataPermissionDepartmentIDs) = _currentUser.CurrentUserInfo.LoginUserRoleDepartment;

            //获取所有部门设置的数据权限
            List<DataDepartment> departmentDataPermissions = _IDataDepartmentRepository.GetDataDepartmentsByDataIDs(DataDepartment_Type.用户, pageData.Items.Select(x => x.UserID).ToArray());

            foreach (var item in pageData.Items)
            {
                var userDepartmentIDs = userDepartmentList.Where(x => x.UserID == item.UserID).Select(x => x.DepartmentID).ToList();
                var departmentNames = departmentList.Where(x => userDepartmentIDs.Contains(x.DepartmentID)).Select(x => x.Name).ToList();
                item.DepartmentNames = departmentNames;

                var userRoleIDs = userRoleList.Where(x => x.UserID == item.UserID).Select(x => x.RoleID).ToList();
                var roleNames = roleList.Where(x => userRoleIDs.Contains(x.RoleID)).Select(x => x.Name).ToList();
                item.RoleNames = roleNames;

                //获取当前循环这条部门数据的所设置的数据权限
                var _currentDataPermissions = departmentDataPermissions.Where(x => x.DataID == item.UserID).Select(x => x.DepartmentID).ToList();

                //设置每一条数据的数据权限的部门名称
                if (_currentDataPermissions.Any(x => x == Gx._NO_DATA_PERMISSION_VALUE))
                {
                    item.SelectDepartmentNames = new List<string>() { "不限" };
                }
                else
                {
                    item.SelectDepartmentNames = departmentList.Where(x => _currentDataPermissions.Contains(x.DepartmentID)).Select(x => x.Name).ToList();
                }
            }

            return pageData;
        }
        #endregion

        #region 重置密码  ResetPassword
        public void ResetPassword(List<int> ids, string pwd)
        {
            _repository.ResetPassword(ids, pwd);
        }
        #endregion

        #region 获取部门中的用户列表  GetUserListByDepartmentID
        public List<UserModel> GetUserListByDepartmentID(int departmentID)
        {
            return _mapping.Entity2Model(_repository.GetUserListByDepartmentID(departmentID));
        }
        #endregion

        #region Insert
        public override UserModel Insert(UserModel model)
        {
            if (_repository.GetLoginNameExists(model.LoginName))
            {
                throw new CustomException("登录名已存在！");
            }

            var res = base.Insert(model);
            _IDataDepartmentRepository.InsertByDataID(DataDepartment_Type.用户, res.UserID, model.SelectDepartmentIDs.ToArray());
            return res;
        }
        #endregion

        #region Update
        public override int Update(UserModel model)
        {
            _IDataDepartmentRepository.UpdateByDataID(DataDepartment_Type.用户, model.UserID, model.SelectDepartmentIDs.ToArray());
            return base.Update(model);
        }
        #endregion

        #region GetByID
        public override UserModel GetByID(int id)
        {
            var item = base.GetByID(id);
            item.SelectDepartmentIDs = _IDataDepartmentRepository.GetDataDepartmentsByDataIDs(DataDepartment_Type.用户, id).Select(x => x.DepartmentID).ToList();

            var where = Expressionable.Create<Role>();
            where = where.And(x => item.RoleIDs.Contains(x.RoleID));
            item.RoleNames = _IRoleRepository.GetSearch(where).Select(x => x.Name).ToList();
            return item;
        }
        #endregion

        #region EditPassword
        public void EditPassword(EditPasswordModel model)
        {
            var userID = _currentUser.CurrentUserInfo.UserID;

            switch (_currentUser.CurrentUserInfo.LoginUserType)
            {
                case LoginUserType.集团:
                    var dbUser = _repository.GetByID(userID);
                    if (dbUser.LoginPassword != Gx.DesEncrypt(model.OldPassword))
                    {
                        throw new CustomException("旧密码输入不正确！");
                    }

                    dbUser.LoginPassword = Gx.DesEncrypt(model.NewPassword);
                    _repository.Update(dbUser);
                    break;

                case LoginUserType.监管部门:
                    var dbRegulatorUser = _IRegulatorUserRepository.GetByID(userID);
                    if (dbRegulatorUser.LoginPassword != Gx.DesEncrypt(model.OldPassword))
                    {
                        throw new CustomException("旧密码输入不正确！");
                    }

                    dbRegulatorUser.LoginPassword = Gx.DesEncrypt(model.NewPassword);
                    _IRegulatorUserRepository.Update(dbRegulatorUser);

                    break;

                case LoginUserType.超级用户:
                    var dbSuperUser = _ISuperUserRepository.GetByID(userID);
                    if (dbSuperUser.LoginPassword != Gx.DesEncrypt(model.OldPassword))
                    {
                        throw new CustomException("旧密码输入不正确！");
                    }

                    dbSuperUser.LoginPassword = Gx.DesEncrypt(model.NewPassword);
                    _ISuperUserRepository.Update(dbSuperUser);
                    break;
            }
        }
        #endregion
    }
}
